import os
from win32com.client import Dispatch


def check_shortcut_validity(lnk_path):
    """ 验证快捷方式有效性 """
    try:
        shell = Dispatch('WScript.Shell')
        shortcut = shell.CreateShortCut(lnk_path)
        target = shortcut.TargetPath

        # 检查目标路径是否存在
        if os.path.exists(target):
            return True, target
        return False, target
    except Exception as e:
        return False, f"解析失败：{str(e)}"


def generate_report(results):
    with open("shortcut_report.csv", "w") as f:
        f.write("快捷方式路径,状态,详细信息\n")
        for item in results:
            f.write(f"{item['path']},{'有效' if item['valid'] else '无效'},{item['detail']}\n")


def scan_shortcuts(folder_path):
    """ 遍历目录检测所有快捷方式 """
    results = []
    for root, _, files in os.walk(folder_path):
        for file in files:
            if file.lower().endswith('.lnk'):
                lnk_path = os.path.join(root, file)
                valid, detail = check_shortcut_validity(lnk_path)
                results.append({
                    "path": lnk_path,
                    "valid": valid,
                    "detail": detail
                })
    return results


if __name__ == "__main__":
    target_folder = "E:/game_backup_test"
    report = scan_shortcuts(target_folder)

    print("检测报告：")
    for item in report:
        status = "有效" if item["valid"] else f"无效（{item['detail']}）"
        print(f"{item['path']} -> {status}")